import 'package:flutter/material.dart';
import 'package:flutter_member/routes/application.dart';
import 'package:flutter_member/stytle/listview_overScrollbehavior.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:loading_animations/loading_animations.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';

class CurriculumDetailsPage extends StatefulWidget {
  final String id;
  CurriculumDetailsPage({Key key,this.id});
  @override
  _CurriculumDetailsPageState createState() => _CurriculumDetailsPageState();
}

class _CurriculumDetailsPageState extends State<CurriculumDetailsPage> {
  var objectId = '';
  get objectid=>widget.id;
  bool view = true;
  CourseDetails _courseDetails;
  List<String> _albumList = [];

  /// 获取课程详情
  Future<void> _getCourseClass() async {
    QueryBuilder<ParseObject> queryPost =
        QueryBuilder<ParseObject>(ParseObject('CourseClass'))
          ..whereStartsWith('objectId', objectid);

    QueryBuilder<ParseObject> queryComment =
        QueryBuilder<ParseObject>(ParseObject('CourseLesson'))
          ..includeObject(['location', 'class'])
          ..whereMatchesQuery('class', queryPost);

    var apiResponse = await queryComment.query();
    if (apiResponse.success) {
      var email = '';
      var tel = '';
      var description = '';
      QueryBuilder<ParseObject> query =
          QueryBuilder<ParseObject>(ParseObject('BranchRoom'))
            ..whereStartsWith('objectId', apiResponse.results.first['location']['objectId'])
            ..includeObject(['branch']);
      var couresRes = await ParseObject('Course').getObject(apiResponse.results.first['class']['course']['objectId']);
      if (couresRes.success) {
        description = couresRes.result['description'];
      }
      var res = await query.query();
      if (res.success) {
        var dataMap = res.results.first;
        if (dataMap['branch']['contacts'] != null) {
          print('dataMap:${dataMap['branch']['contacts']}');
          for (var value in dataMap['branch']['contacts']) {
            if (value['type'] == 'tel' && value['type'] != null) {
              tel = value['value'];
            } else if (value['type'] == 'fax' && value['type'] != null) {
              tel = tel + ' / ' + value['value'];
            } else if (value['type'] == 'email' && value['type'] != null) {
              email = value['value'];
            }
          }
        }
        //獲取相冊
        QueryBuilder<ParseObject> queryAlbum = QueryBuilder<ParseObject>(ParseObject('AlbumPhoto'))
              ..whereRelatedTo('images', 'Alum', apiResponse.results.first['class']['album']['objectId']);
        var albums = await queryAlbum.query();
        if (albums.success) {
          setState(() {
            _albumList.clear();
            for (var album in albums.results) {
              _albumList.add(album['src'] != null ? album['src']['url'] : null);
            }
          });
        }
        var endDate = apiResponse.results.first['class']['endDate'];
        var startDate = apiResponse.results.first['class']['startDate'];
        setState(() {
          _courseDetails = CourseDetails(
              apiResponse.results.first['class']['objectId'],
              apiResponse.results.first['class']['title'],
              '${startDate.month}月${startDate.day}日-${endDate.month}月${endDate.day}日',
              apiResponse.results.first['class']['capacity'] - apiResponse.results.first['class']['enrolled'],
              //剩餘名額
              dataMap['branch']['address'],
              double.parse(apiResponse.results.first['class']['fee'].toString()),
              tel,
              email,
              description);
        });
      }
    }
  }

  Widget _swiperBuilder(int index) {
    return (_albumList[index] != null
        ? Image.network(
            _albumList[index],
            fit: BoxFit.fill,
          )
        : Image.asset(
            'images/noimg.jpg',
            fit: BoxFit.fill,
          ));
  }

  @override
  void initState() {
    super.initState();
    _getCourseClass();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    setState(() {
      objectId = widget.id;
//      Map data = ModalRoute.of(context).settings.arguments;
//      objectId = data['objectId'];
//      view = data['v'] == 0 ? false : true;

    });
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    return Scaffold(
      body: Container(
        child: ScrollConfiguration(
            behavior: OverScrollBehavior(),
            child: Stack(
              children: <Widget>[
                Stack(
                  children: <Widget>[
                    //頂部相冊
                    Container(
                        width: MediaQuery.of(context).size.width,
                        height: ScreenUtil().setHeight(260),
                        child: _albumList.length == 0
                            ? LoadingBouncingLine.circle(
                                borderColor: Colors.lightBlue,
                                backgroundColor: Colors.lightBlue,
                              )
                            : Swiper(
                                itemBuilder:
                                    (BuildContext context, int index) =>
                                        _swiperBuilder(index),
                                itemCount: _albumList.length,
                                pagination: SwiperPagination(
                                    margin: EdgeInsets.only(bottom: 30),
                                    builder: DotSwiperPaginationBuilder(
                                      color: Colors.black54,
                                      activeColor: Colors.white,
                                    )),
                                //control: SwiperControl(),
                                scrollDirection: Axis.horizontal,
                                autoplay: true,
                                onTap: (index) => print('点击了第$index个a'),
                              )),
                    Padding(
                      padding: EdgeInsets.only(top: 15),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          IconButton(
                            icon: Icon(
                              Icons.arrow_back,
                              color: Colors.white,
                              size: 30,
                            ),
                            onPressed: () => Navigator.pop(context),
                          )
                        ],
                      ),
                    ),
                  ],
                ),
                contentWidget(width, height)
              ],
            )),
      ),
    );
  }

  Widget gradientButton() {
    return Container(
      width: ScreenUtil().setWidth(200),
      height: ScreenUtil().setHeight(50),
      margin: EdgeInsets.fromLTRB(0, 10, 0, 8),
      decoration: BoxDecoration(
          gradient: LinearGradient(colors: [Color(0xff82b518), Color(0xff3e73b7)]),// 渐变色
          borderRadius: BorderRadius.circular(50)
      ),
      child: RaisedButton(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(50)
        ),
        color: Colors.transparent, // 设为透明色
        elevation: 0, // 正常时阴影隐藏
        highlightElevation: 0, // 点击时阴影隐藏
      onPressed: ()=>Application.jump(context, "/curriculum/registration/:${objectId}"),
        child: Container(
          alignment: Alignment.center,
          child:Row(
            mainAxisAlignment:MainAxisAlignment.center,
            children: <Widget>[
            ImageIcon(AssetImage('images/group.png'),color: Color(0xffffffff),size: ScreenUtil().setSp(23),),
            SizedBox(width: 10),
            Text('登記報讀課程', style: TextStyle(color: Colors.white, fontSize: ScreenUtil().setSp(16),fontWeight: FontWeight.bold,fontFamily:"SemiBold",),),
          ],) //
        ),
      ),
    );
  }

  //課程詳情信息
  Widget contentWidget(width, height) {
    return Container(
        padding: EdgeInsets.only(top: ScreenUtil().setHeight(240)),
        child: Scrollbar(
          child: Stack(
            children: <Widget>[
              Container(
                width: width,
                height: height,
                decoration: BoxDecoration(
                    color: Color(0xffE5EEF6),
                    borderRadius: BorderRadius.all(Radius.circular(20))),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(0.0, 5, 0.0, 0.0),
                height: height,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(20))),
                child: ListView(
                  children: <Widget>[
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          child: Column(
                            children: <Widget>[
                              Container(
                                padding: EdgeInsets.only(left: 30,right: 30),
                                child: Row(
                                  children: <Widget>[
                                    teachingCourses(),
                                    SizedBox(width: 10),
                                    Text(
                                      _courseDetails == null
                                          ? '暫無'
                                          : _courseDetails.title,
                                      style: TextStyle(
                                        fontSize: ScreenUtil().setSp(18),
                                        color: Color(0xff2D7FC7),
                                        fontWeight: FontWeight.bold,
                                        fontFamily:"SemiBold",
                                      ),
                                    )
                                  ],
                                ),
                              ),
                              Container(
                                padding: EdgeInsets.only(top: 10,left: 30,right: 30),
                                child: Row(
                                  children: <Widget>[
                                    ImageIcon(
                                      AssetImage('images/course_date.png'),
                                      color: Color(0xffFFC82C),
                                      size: ScreenUtil().setSp(20),
                                    ),
                                    SizedBox(width: 10),
                                    Column(
                                      children: <Widget>[
                                        curriculumDetailsContent(
                                            width,
                                            _courseDetails == null
                                                ? '暫無'
                                                : _courseDetails.endStartDate,
                                            ScreenUtil().setSp(13),
                                            Color(0xff154D7C)),
                                        curriculumDetailsContent(
                                            width,
                                            '(逢星期六 17:30 - 19:30)',
                                            ScreenUtil().setSp(13),
                                            Color(0xff154D7C)),
                                      ],
                                    )
                                  ],
                                ),
                              ),
                              Container(
                                padding: EdgeInsets.only(top: 5,left: 30,right: 30),
                                child: Row(
                                  children: <Widget>[
                                    ImageIcon(
                                      AssetImage('images/course_address.png'),
                                      color: Color(0xffFFC82C),
                                      size: ScreenUtil().setSp(20),
                                    ),
                                    SizedBox(
                                      width: 10,
                                    ),
                                    curriculumDetailsContent(
                                        width,
                                        _courseDetails == null
                                            ? '暫無地址'
                                            : _courseDetails.address,
                                        ScreenUtil()
                                            .setSp(13),
                                        Color(0xff154D7C)),
                                  ],
                                ),
                              ),
                              Container(
                                padding: EdgeInsets.only(top: 5,left: 30,right: 30),
                                child: Row(
                                  children: <Widget>[
                                    ImageIcon(
                                      AssetImage('images/course_price.png'),
                                      color: Color(0xffFFC82C),
                                      size: ScreenUtil().setSp(20),
                                    ),
                                    SizedBox(
                                      width: 10,
                                    ),
                                    curriculumDetailsContent(
                                      width,
                                      '課程費用：\$ ${_courseDetails == null ? '' : _courseDetails.fee}（包括雜費及材料費）',
                                      ScreenUtil()
                                          .setSp(13),
                                      Color(0xff154D7C),
                                    ),
                                  ],
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(top: 10,right: 30,left: 30,bottom: 10),
                                child: Row(
                                  children: <Widget>[
                                    _courseDetails == null
                                        ? Text(
                                      '名額剩餘 ： 位',
                                      style: TextStyle(color: Color(0xfff40e29),fontSize: ScreenUtil()
                                          .setSp(13),fontFamily:"SemiBold",),
                                    )
                                        : _courseDetails.places <= 5
                                        ? Text(
                                      '名額剩餘 ：${_courseDetails.places}位',
                                      style:
                                      TextStyle(color: Color(0xfff40e29),fontSize: ScreenUtil()
                                          .setSp(13),fontFamily:"SemiBold",),
                                    )
                                        : Text(
                                      '名額剩餘 ：5位以上',
                                      style: TextStyle(
                                        color: Color(0xffbcbcbc),fontSize: ScreenUtil()
                                          .setSp(13),fontWeight: FontWeight.w600,
                                        fontFamily:"SemiBold",
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              Container(
                                decoration: bottomBorderLine(),
                                width: width-60,
                              ),
                            ],
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.only(top: 10,left: 30,right:30),
                          child: Column(
                            children: <Widget>[
                              curriculumDetailsTitle(width, '簡介',ScreenUtil().setSp(18)),
                              Container(
                                width: width,
                                child: curriculumDetailsContent(
                                    width,
                                    _courseDetails == null
                                        ? '暫無'
                                        : _courseDetails.description,
                                    ScreenUtil().setSp(13),
                                    Color(0xff9C9C9C)),
                              ),
                              Container(
                                margin: EdgeInsets.only(top: 10,bottom: 10),
                                decoration: bottomBorderLine(),
                                width: width-60,
                              ),
                            ],
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.only(right: 30,left: 30),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: <Widget>[
                              curriculumDetailsTitle(width, '報名方式',ScreenUtil().setSp(18)),
                              Column(
                                children: <Widget>[
                                  Container(
                                    margin: EdgeInsets.only(top: 10),
                                    child:Row(
                                      children: <Widget>[
                                        ImageIcon(
                                          AssetImage('images/course_address.png'),
                                          color: Color(0xffFFC82C),
                                          size: ScreenUtil().setSp(20),
                                        ),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        curriculumDetailsContent(
                                            width,
                                            _courseDetails == null
                                                ? '暫無'
                                                : _courseDetails.address,
                                            ScreenUtil().setSp(13),
                                            Color(0xff154D7C)),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 10),
                                    child: Row(
                                      children: <Widget>[
                                        ImageIcon(
                                          AssetImage('images/course_phone.png'),
                                          color: Color(0xffFFC82C),
                                          size: ScreenUtil().setSp(20),
                                        ),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        curriculumDetailsContent(
                                            width,
                                            _courseDetails == null
                                                ? '暫無'
                                                : _courseDetails.phone,
                                            ScreenUtil().setSp(13),
                                            Color(0xff154D7C)),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 10),
                                    child: Row(
                                      children: <Widget>[
                                        ImageIcon(
                                          AssetImage('images/course_mail.png'),
                                          color: Color(0xffFFC82C),
                                          size: ScreenUtil().setSp(20),
                                        ),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        curriculumDetailsContent(
                                            width,
                                            _courseDetails == null
                                                ? '暫無'
                                                : _courseDetails.email,
                                            ScreenUtil().setSp(13),
                                            Color(0xff154D7C)),
                                      ],
                                    ),
                                  ),
                                  view
                                      ? Column(
                                    children: <Widget>[
                                      SizedBox(
                                        height: 20,
                                      ),
                                      Text(
                                        '或點擊以下按鈕等級報名',
                                        style: TextStyle(
                                          color: Color(0xff154D7C),
                                          fontSize: ScreenUtil().setSp(13),
                                          fontWeight: FontWeight.bold,
                                          fontFamily: "SemiBold",),
                                      ),
                                      gradientButton()
                                    ],
                                  )
                                      : Column()
                                ],
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ));
  }
  //持教課程
  Widget teachingCourses(){
    return Container(
      child: Align(
        alignment: Alignment.centerLeft,
        child: Container(
            decoration: BoxDecoration(
                color: Color(0xff93BB24),
                borderRadius: BorderRadius.circular(50)
            ),
            width: ScreenUtil().setWidth(75),
            height: ScreenUtil().setHeight(26),
            child:Center(
              child:  Text(
                '持教課程',
                style: TextStyle(
                    fontFamily: "SemiBold",
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                    fontSize: ScreenUtil().setSp(13)
                ),
              ),
            )
        ),
      ),
    );
  }
//課程詳情內容文本
  Widget curriculumDetailsContent(double width,String text,double fontSize,Color color){
    return Container(
      margin: EdgeInsets.only(top: 5),
      width: width-110,
      child: Text(
        text,
        style: TextStyle(
          fontSize: fontSize,
          fontWeight: FontWeight.bold,
          color: color,
          fontFamily:"SemiBold",
        ),
        softWrap: true,
      ),
    );
  }
  //課程詳情標題文本
  Widget curriculumDetailsTitle(double width,String title,double fontsize){
    return Container(
      width: width,
      child: Text(
        title,
        style: TextStyle(
            fontSize: fontsize,
            fontWeight: FontWeight.bold,
            color: Color(0xff93BB24)
        ),
      ),
    );
  }
  //底部邊框線
  BoxDecoration bottomBorderLine(){
    return BoxDecoration(
      border: Border(
        bottom: BorderSide(
            color: Color(0xffD8D8D8),
            width: 1,
            style: BorderStyle.solid),
      ),
    );
  }
}

class CourseDetails {
  final String objectId;
  final String title;
  final String endStartDate;
  final int places;
  final String address;
  final double fee;//費用
  final String phone;
  final String email;
  final String description;

  CourseDetails(this.objectId, this.title, this.endStartDate, this.places,
      this.address, this.fee, this.phone, this.email, this.description);
}
